import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  Image,
  ScrollView,
  ActivityIndicator,
  StatusBar,
  Platform,
  BackHandler,
} from 'react-native';
import { Toast } from '@ant-design/react-native';
import { getStatusBarHeight } from '../../../utils/statusBarHeight';
import { getBatchOrderDetailApi } from './api';
import fanhui from '../../../assets/fanhui.png';

interface BatchDetailScreenProps {
  route: {
    params: {
      id: string;
    };
  };
  navigation: {
    goBack: () => void;
  };
}

const BatchDetailScreen: React.FC<BatchDetailScreenProps> = ({ route, navigation }) => {
  const { id } = route.params;
  const [loading, setLoading] = useState(true);
  const [batchDetail, setBatchDetail] = useState<any>(null);
  const [selectedTaskIndex, setSelectedTaskIndex] = useState<number>(0);

  // 获取批次详情
  const getBatchDetail = async () => {
    try {
      setLoading(true);
      const params = { batch_order_id: id };
      console.log('请求批次详情接口: /app/BatchOrder/getBatchOrderDetail', params);
      const res = await getBatchOrderDetailApi(params);
      console.log('批次详情接口返回:', res);

      if (res && res.data) {
        setBatchDetail(res.data);
        // 默认选择第一个工序
        if (res.data.task_list && res.data.task_list.length > 0) {
          setSelectedTaskIndex(0);
        }
      } else {
        Toast.fail(res?.msg || '获取批次详情失败', 1);
      }
    } catch (e: any) {
      console.log('获取批次详情接口异常:', e);
      Toast.fail(e.msg || e.message || '获取批次详情失败', 1);
    } finally {
      setLoading(false);
    }
  };

  // 返回上一页
  const handleGoBack = () => {
    navigation.goBack();
  };

  // 处理Android硬件返回键
  useEffect(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
      // 拦截返回键，调用自定义返回函数
      handleGoBack();
      return true; // 返回true表示已处理该事件，阻止默认行为
    });

    return () => backHandler.remove();
  }, []);

  useEffect(() => {
    getBatchDetail();
  }, [id]);

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar
          barStyle="dark-content"
          backgroundColor="#fff"
          translucent={true}
        />
        <View style={styles.headerContainer}>
          <View style={styles.header}>
            <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
              <Image source={fanhui} style={styles.backIcon} />
            </TouchableOpacity>
            <Text style={styles.title}>进度查看</Text>
            <View style={styles.placeholder} />
          </View>
        </View>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#007AFF" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </SafeAreaView>
    );
  }

  const selectedTask = batchDetail?.task_list?.[selectedTaskIndex];

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar
        barStyle="dark-content"
        backgroundColor="#fff"
        translucent={true}
      />
      {/* 顶部导航栏 */}
      <View style={styles.headerContainer}>
        <View style={styles.header}>
          <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
            <Image source={fanhui} style={styles.backIcon} />
          </TouchableOpacity>
          <Text style={styles.title}>进度查看</Text>
          <View style={styles.placeholder} />
        </View>
      </View>

      {/* 内容区域 */}
      <View style={styles.content}>
        {batchDetail ? (
          <>
            {/* 固定区域 - 不滚动 */}
            <View style={styles.fixedSection}>
              {/* 批次信息头部 */}
              <View style={styles.batchHeader}>
                <View style={styles.batchNumContainer}>
                  <Text style={styles.batchNum} numberOfLines={2} ellipsizeMode="tail">
                    {batchDetail.batch_order_num}
                  </Text>
                </View>
                <View style={styles.batchProgressContainer}>
                  <Text style={styles.batchProgress}>{batchDetail.percent || 0}%</Text>
                </View>
              </View>

              {/* 工序流程图 */}
              {batchDetail.task_list && batchDetail.task_list.length > 0 && (
                <View style={styles.processSection}>
                  <ScrollView
                    horizontal
                    showsHorizontalScrollIndicator={false}
                    style={styles.processScrollView}
                  >
                    <View style={styles.processContainer}>
                      {batchDetail.task_list.map((task: any, index: number) => (
                        <View key={task.id} style={styles.processItemContainer}>
                          <TouchableOpacity
                            style={[
                              styles.processItem,
                              { backgroundColor: task.process_color || '#ccc' },
                              selectedTaskIndex === index && styles.selectedProcessItem
                            ]}
                            onPress={() => setSelectedTaskIndex(index)}
                          >
                            <View style={styles.processTextContainer}>
                              <Text style={styles.processNum}>{task.mbom_num}</Text>
                              <Text style={styles.processName} numberOfLines={2}>{task.process_name}</Text>
                            </View>
                            {selectedTaskIndex === index && (
                              <View style={styles.completedIcon}>
                                <Text style={styles.checkmark}>✓</Text>
                              </View>
                            )}
                          </TouchableOpacity>
                          {index < batchDetail.task_list.length - 1 && (
                            <View style={styles.processArrow}>
                              <Text style={styles.arrowText}>→</Text>
                            </View>
                          )}
                        </View>
                      ))}
                    </View>
                  </ScrollView>
                </View>
              )}
            </View>
            <Text style={styles.sectionTitle}>工序详情</Text>
            {/* 滚动区域 - 工序详情 */}
            {selectedTask ? (
              <ScrollView style={styles.scrollableSection}>
                <View style={styles.taskDetailSection}>
                  <View style={styles.taskDetailContainer}>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>工序进度：</Text>
                      <Text style={styles.infoValue}>{selectedTask.percent || 0}%</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>计划数量：</Text>
                      <Text style={styles.infoValue}>{selectedTask.quantity || '-'}</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>加工数量：</Text>
                      <Text style={styles.infoValue}>{selectedTask.work_quantity || '-'}</Text>
                    </View>
                    {/* <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>让步接收：</Text>
                      <Text style={styles.infoValue}>{selectedTask.accept_quantity || '-'}</Text>
                    </View> */}
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>报废数量：</Text>
                      <Text style={styles.infoValue}>{selectedTask.fatal_quantity || '-'}</Text>
                    </View>
                    {/* <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>返工数量：</Text>
                      <Text style={styles.infoValue}>{selectedTask.rework_quantity || '-'}</Text>
                    </View> */}
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>批次号：</Text>
                      <Text style={styles.infoValue}>{selectedTask.batch_order_num || '-'}</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>工作区域：</Text>
                      <Text style={styles.infoValue}>{selectedTask.aps_room_name || '-'}</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>操作人员：</Text>
                      <Text style={styles.infoValue}>{selectedTask.work_user_name || '-'}</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>设备编码：</Text>
                      <Text style={styles.infoValue}>{selectedTask.aps_device_num || '-'}</Text>
                    </View>
                    <View style={styles.infoRow}>
                      <Text style={styles.infoLabel}>工位编码：</Text>
                      <Text style={styles.infoValue}>{selectedTask.work_station_num || '-'}</Text>
                    </View>
                  </View>
                </View>
              </ScrollView>
            ) : (
              <View style={styles.emptyTaskContainer}>
                <Text style={styles.emptyTaskText}>暂无工序数据</Text>
              </View>
            )}
          </>
        ) : (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>暂无批次详情数据</Text>
          </View>
        )}
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  headerContainer: {
    backgroundColor: '#fff',
    paddingTop: getStatusBarHeight(),
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: 50,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
    paddingHorizontal: 16,
  },
  backButton: {
    width: 44,
    height: 44,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backIcon: {
    width: 24,
    height: 24,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  placeholder: {
    width: 44,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  content: {
    flex: 1,
    padding: 10,
  },
  fixedSection: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
    overflow: 'visible',
  },
  scrollableSection: {
    flex: 1,
  },
  detailContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
  },
  batchHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 5,
    paddingBottom: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    minHeight: 50,
  },
  batchNumContainer: {
    flex: 1,
    marginRight: 12,
    justifyContent: 'center',
  },
  batchNum: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    lineHeight: 24,
  },
  batchProgressContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    minWidth: 60,
    height: 50,
  },
  batchProgress: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#007AFF',
    textAlign: 'right',
  },
  processSection: {
    marginBottom: 0,
    overflow: 'visible',
    height: 70,
  },
  processScrollView: {
    overflow: 'hidden',
    flex: 1,
  },
  processContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'nowrap',
    paddingRight: 2,

  },
  processItemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  processItem: {
    minWidth: 60,
    maxWidth: 120,
    height: 60,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
    marginHorizontal: 2,
    paddingHorizontal: 7,
  },
  processTextContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  processNum: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 2,
  },
  processName: {
    fontSize: 10,
    color: '#fff',
    textAlign: 'center',
    lineHeight: 12,
    flexShrink: 1,
  },
  completedIcon: {
    position: 'absolute',
    top: -7,
    right: -7,
    backgroundColor: '#007AFF',
    borderRadius: 8,
    width: 16,
    height: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkmark: {
    fontSize: 10,
    color: '#fff',
    fontWeight: 'bold',
  },
  processArrow: {
    marginHorizontal: 7,
  },
  arrowText: {
    fontSize: 16,
    color: '#007AFF',
    fontWeight: 'bold',
  },
  selectedProcessItem: {
    borderWidth: 3,
    borderColor: '#007AFF',
    elevation: 3,
    shadowColor: '#007AFF',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  },
  taskDetailSection: {
    marginBottom: 0,
  },
  taskDetailScroll: {
    maxHeight: 300,
  },
  taskDetailContainer: {
    backgroundColor: '#f8f8f8',
    borderRadius: 8,
    padding: 0,
    paddingRight: 10,
    paddingLeft: 10,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 0,
    paddingBottom: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
    borderBottomWidth: 0.5,
    borderBottomColor: '#f0f0f0',
  },
  infoLabel: {
    fontSize: 14,
    color: '#666',
    fontWeight: '500',
  },
  infoValue: {
    fontSize: 14,
    color: '#333',
    flex: 1,
    textAlign: 'right',
    marginLeft: 16,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 16,
    color: '#999',
  },
  emptyTaskContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 40,
    backgroundColor: '#f8f8f8',
    borderRadius: 8,
    marginTop: 10,
  },
  emptyTaskText: {
    fontSize: 16,
    color: '#999',
  },
});

export default BatchDetailScreen; 